package vip.guzb.sample.threadpool.step01;

import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * 只有一个线程的线程池
 * 池中的唯一线程, 且默认永远不停止，直到调用 shutdown 方法
 *
 * @author 顾志兵
 * @mail ipiger@163.com
 * @since 2024-04-08
 */
public class SingleThreadPoolExecutor3 implements Executor {

    private final Queue<Runnable> tasks = new LinkedBlockingDeque<>();

    private volatile boolean shutdownFlag = false;

    @Override
    public void execute(Runnable task) {
        tasks.offer(task);
    }

    public SingleThreadPoolExecutor3() {
        Thread runner = new Thread(() -> {
            Runnable task;
            while (true) {
                if (shutdownFlag) {
                    break;
                }
                task = tasks.poll();
                if (task != null) {
                    task.run();
                    continue;
                }
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        });
        runner.start();
    }

    public void shutdown() {
        System.out.println("手动关闭线程池");
        this.shutdownFlag = true;
    }
}
